<?php
namespace api\modules\v1\models\gift;

use api\modules\v1\models\Common;
use api\modules\v1\models\friend\Friend;
use api\modules\v1\models\user\User;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\im\Im;
use common\models\Status;
use common\models\userFund\UserMoneyLog;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use Yii;
/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class Gift extends \common\models\gift\Gift
{

    /**
     * 列表
     * @return array
     */
    public function getList(){
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $page = Yii::$app->request->get('page',1);
            $size = Yii::$app->request->get('size',20);
            $categoryId = Yii::$app->request->get('category_id','');

            $andWhere = [];
            $where['status'] = Status::COMMON_RADIO_YES;
            $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;
            $where = ["is_delete" => Status::COMMON_IS_NOT_DELETE];
            if ($categoryId) {
                $where['category_id'] = $categoryId;
            }

            static::setPaginationForApi($page);
            $offset = ($page - 1) * $size;
            $list = static::getObjectByAndWhere($where,$andWhere,['id','name','coin','icon','cartoon_url'],'id ASC',$offset,$size)->with()->asArray()->all();

            $result = [];
            foreach ($list as $k => $v) {
                $tmp = [
                    'id' => (int) $v['id'],
                    'name' => (string) $v['name'],
                    'icon' => $v['icon'] ? $this->getImages($v['icon']) : '',
                    'coin' => (double) $v['coin'],
                    'cartoon_url' => $v['cartoon_url'] ? $this->getImages($v['cartoon_url']) : '',
                ];
                $result[] = $tmp;
            }
            $data['data'] = $result;
            $data['coin'] = $user['coin'];
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 赠送礼物
     * @return array
     */
    public function sendGift() {

        $user = Yii::$app->getUser()->getIdentity()->toArray();
        $trans = static::getDb()->beginTransaction();
        $userId = $user['id'];
        try {
            $config = static::getCommonByKey('switch_gift');
            if ($config == Status::COMMON_RADIO_NO) {
                throw new Exception('系统维护，暂停送礼物！');
            }

            if (!$userId) {
                throw new Exception('未知用户，不能赠送猎物！');
            }

            CacheKeys::checkFrequency($userId,1);

            $giftId = Yii::$app->request->post('id',0);
            $txCode = Yii::$app->request->post('tx_code','');


            $exists = Yii::$app->redis->get(CacheKeys::IM_SEND_GIFT . $userId);
            if($exists){
                throw new Exception('您的速度太快了！');
            }
            Yii::$app->redis->set(CacheKeys::IM_SEND_GIFT . $userId, true);

            if(!$giftId) {
                throw new Exception('未知礼物信息！');
            }

            $giftInfo = static::getOneByWhere(['id' => $giftId]);
            if(!$giftInfo) {
                throw new Exception('未知礼物信息！');
            }

            if(!$txCode) {
                throw new Exception('接收方账号不能为空！');
            }

            if($user['coin'] < $giftInfo['coin']) {
                throw new Exception('金币不足，无法赠送！');
            }


            $receiveUser = User::getOneByWhere(['tx_code' => $txCode]);
            if (empty($receiveUser)) {
                throw new Exception("赠送的用户不存在！");
            }

            // 是否好友
            $userFriendInfo = Friend::getOneByWhere([
                'user_id' => $userId,
                'friend_id' => $receiveUser['id'],
            ]);

            if (empty($userFriendInfo)) {
                throw new Exception("你和他不是好友，无法赠送！");
            }

            $transInfo = $this->_send($user, $giftInfo, $receiveUser);
            if (empty($transInfo)) {
                throw new Exception("转账失败");
            }

            $imModel = new Im();
            // 发送消息
            $userMessage['message_type'] = Status::MESSAGE_TYPE_USER_SEND_GIFT;
            $userMessage['type'] = Status::MESSAGE_TYPE_USER_SEND_GIFT;
            $userMessage['gift_id'] = $giftInfo['id'];
            $userMessage['coin'] = $giftInfo['coin'];
            $userMessage['tx_code'] = $user['tx_code'];
            $userMessage['user_phone'] = $user['login_name'];
            $userMessage['receive_tx_code'] = $receiveUser['tx_code'];
            $userMessage['receive_nick_name'] = $receiveUser['nick_name'] ?: '';
            $userMessage['gift_icon'] = static::getImages($giftInfo['icon']) ?: '';
            $userMessage['gift_name'] = $giftInfo['name'] ?: '';
            $userMessage['gift_cartoon'] = static::getImages($giftInfo['cartoon_url']) ?: '';;
            $userMessage['time'] = date('Y-m-d H:i:s');
            $userMessage['unix_time'] = time();
            $imRes = $imModel->sendUserMessage($receiveUser['tx_code'], $userMessage, $user['tx_code']);
            if (!$imRes) {
                throw new Exception("转账异常");
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '赠送成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI($e->getCode() ? $e->getCode() : 1, $e->getMessage());
        }
        finally {
            Yii::$app->redis->del(CacheKeys::IM_SEND_GIFT . $userId);
        }
    }

    // 送礼物
    public function _send(
        $userInfo = [],
        $giftInfo = [],
        $receiveUser = []
    ) {
        if (!$userInfo || !$giftInfo || !$receiveUser) {
            return null;
        }

        // 加入礼物日志表
        $insertData['gift_id'] = $giftInfo['id'];
        $insertData['coin'] = $giftInfo['coin'];
        $insertData['user_id'] = (int) $userInfo['id'];
        $insertData['user_tx_code'] = $userInfo['tx_code'];
        $insertData['user_code'] = $userInfo['user_code'];
        $insertData['receive_user_id'] = (int) $receiveUser['id'];
        $insertData['receive_user_code'] = $receiveUser['user_code'];
        $insertData['receive_user_tx_code'] = $receiveUser['tx_code'];
        $insertData['create_time'] = date('Y-m-d H:i:s');

        $resInsert = GiftLog::insertData($insertData);
        if ($resInsert === false) {
            throw new Exception('系统异常，请稍后尝试！');
        }

        $insertData['id'] = (int) $resInsert;

        // 拼接返回信息
        $return = $insertData;

        // 发送方 余额信息
        UserMoneyLog::record(
            $userInfo['id'],
            Status::PROP_TYPE_COIN,
            Status::COIN_LOG_TYPE_SEND_GIFT,
            -1 * $giftInfo['coin'],
            Status::COIN_LOG_TYPE_MAP[Status::COIN_LOG_TYPE_SEND_GIFT] ?? '',
            '赠送礼物',
            $resInsert
        );

        // 接收方 余额信息  礼物的五折进行提现
        UserMoneyLog::record(
            $receiveUser['id'],
            Status::PROP_TYPE_MONEY,
            Status::MONEY_LOG_TYPE_RECEIVE_GIFT,
            $giftInfo['coin'] * 0.05,
            Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_RECEIVE_GIFT] ?? '',
            '接受礼物',
            $resInsert
        );
        return $return;
    }
}
